package net.sea.setup.ui.wizard.impl.cfg;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;

import net.sea.commons.constants.AppConstants;
import net.sea.commons.context.AppContext;
import net.sea.setup.config.custom.CustomConfig;
import net.sea.setup.ui.common.SelectFile;
import net.sea.setup.ui.wizard.IWizardPage.PageResult;

/**
 * 
 * 配置信息抽象页面
 *
 * @author huachengwu 
 */
public abstract class AbstractCfgPanel extends JPanel {
	private static final long serialVersionUID = 7688770602512042278L;

	// 应用上下文对象
	protected AppContext contextInst = AppContext.getInstance();

	/**
	 * 验证输入项是否正确
	 * 
	 * @return true-验证通过，false-验证失败
	 */
	public abstract PageResult validateInput();

	/**
	 * 创建配置信息
	 * 
	 * @return 自定义配置
	 */
	public abstract CustomConfig buildCfg();

	/**
	 * 创建页面
	 */
	protected abstract void create();

	/**
	 * 验证是否是合法的端口号
	 * 
	 * @param port
	 *            端口号
	 * @return true-是，false-否
	 */
	protected boolean isPort(String port) {
		try {
			int p = Integer.parseInt(port);
			if (p >= 0 && p <= 65535) {
				return true;
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}

	/**
	 * 验证是否为合法的IP
	 * 
	 * @param ip
	 *            IP地址
	 * @return true-是，false-否
	 */
	protected boolean isIP(String ip) {
		Pattern pattern = Pattern
				.compile("([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}");
		Matcher matcher = pattern.matcher(ip);
		return matcher.matches();
	}

	/**
	 * 选择目录
	 * 
	 * @param textField
	 *            设置目录的文本框
	 */
	protected void selectFolder(JTextField textField) {
		SelectFile selectFile = new SelectFile(JFileChooser.OPEN_DIALOG, false,
				JFileChooser.DIRECTORIES_ONLY, "请选择", "打开");
		selectFile.getFileChooser().setCurrentDirectory(
				new File(AppConstants.SYSTEM_PATH));
		File file = selectFile.getSelectedFile();
		if (file != null) {
			textField.setText(file.getAbsolutePath());
		}
	}
}
